package com.ruoyi.web.controller.TiebaChat.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.controller.TiebaChat.domain.TiebaChat;
import com.ruoyi.web.controller.TiebaChat.mapper.TiebaChatMapper;
import com.ruoyi.web.controller.TiebaChat.params.TiebaChatListParam;
import com.ruoyi.web.controller.TiebaChat.service.ITiebaChatService;
import com.ruoyi.web.controller.TiebaChat.vo.ChatMessageReq;
import com.ruoyi.web.controller.TiebaChat.vo.TiebaChatResp;
import com.ruoyi.web.controller.TiebaChatUser.domain.TiebaChatUser;
import com.ruoyi.web.controller.TiebaChatUser.mapper.TiebaChatUserMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 贴吧聊天Controller
 *
 * @author yong
 * @date 2025-03-09
 */
@Api(tags = "用户-聊天内容")
@RestController
@RequestMapping("/tiebaChat/TiebaChat")
public class TiebaChatController extends BaseController {
    @Autowired
    private ITiebaChatService tiebaChatService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private TiebaChatUserMapper chatUserMapper;

    /**
     * 查询贴吧聊天列表
     */
    @ApiOperation("查询聊天列表")
//    @PreAuthorize("@ss.hasPermi('tiebaChat:TiebaChat:list')")
    @GetMapping("/list")
//    @Anonymous
    public TableDataInfo list(TiebaChatListParam chatListParam) {
        startPage();
        // 查询条件：当前用户和聊天对象之间的聊天记录
        QueryWrapper<TiebaChat> queryWrapper = new QueryWrapper<>();
        // 当前用户ID
        Long currentUserId = getUserId();
        // 聊天对象ID
        Long otherUserId = chatListParam.getUserOtherId();
        // 查询条件：双方的聊天记录
        queryWrapper.or(wrapper -> wrapper.eq("user_id", currentUserId).eq("user_other_id", otherUserId))
                .or(wrapper -> wrapper.eq("user_id", otherUserId).eq("user_other_id", currentUserId));
        // 查询聊天记录
        List<TiebaChat> list = tiebaChatService.list(queryWrapper);

        // 重组数据
        List<TiebaChatResp> chatResps = new ArrayList<>();
        for (TiebaChat chat : list) {
            // 查询当前用户信息
            SysUser currentUser = sysUserMapper.selectUserById(currentUserId);
            // 查询聊天对象信息
            SysUser otherUser = sysUserMapper.selectUserById(otherUserId);

            TiebaChatResp tiebaChatResp = new TiebaChatResp();
            tiebaChatResp.setUserId(currentUserId);
            tiebaChatResp.setUserImage(currentUser.getAvatar());
            tiebaChatResp.setUserName(currentUser.getUserName());
            tiebaChatResp.setReceiverId(chat.getReceiverId());
            tiebaChatResp.setSenderId(chat.getSenderId());
            tiebaChatResp.setUserOtherImage(otherUser.getAvatar());
            tiebaChatResp.setOtherUserName(otherUser.getUserName());
            tiebaChatResp.setMessage(chat.getMessage());
            tiebaChatResp.setStatus(chat.getStatus());
            tiebaChatResp.setMessageType(chat.getMessageType());
            tiebaChatResp.setUserOtherId(otherUserId);
            tiebaChatResp.setCreateTime(chat.getCreateTime());

            chatResps.add(tiebaChatResp);
        }
        // 按时间倒序排列
        chatResps = chatResps.stream().sorted(Comparator.comparing(TiebaChatResp::getCreateTime)).collect(Collectors.toList());

        return getDataTable(chatResps);
    }

    /**
     * 新增贴吧聊天
     */
    @ApiOperation("新增贴吧聊天")
    @Log(title = "贴吧聊天", businessType = BusinessType.INSERT)
    @PostMapping("/addMessage")
    public AjaxResult add(@RequestBody ChatMessageReq messageReq) {
        // 创建新的聊天记录对象
        TiebaChat chat = new TiebaChat();
        chat.setUserId(getUserId());
        chat.setSenderId(getUserId());
        chat.setDeptId(getDeptId());
        chat.setMessage(messageReq.getMessage());
        chat.setUserOtherId(messageReq.getUserOtherId());
        chat.setReceiverId(messageReq.getReceiverId());
        chat.setCreateTime(new Date()); // 设置创建时间

        // 保存新的聊天记录
        boolean saveResult = tiebaChatService.save(chat);
        if (!saveResult) {
            return AjaxResult.error("保存聊天记录失败");
        }

        // 更新最后一条信息
        // 找到对应的 TiebaChatUser 记录
        TiebaChatUser chatUser = new TiebaChatUser();
        chatUser.setUserId(getUserId()); // 当前用户
        chatUser.setChatUserId(messageReq.getUserOtherId()); // 聊天对象
        chatUser.setLastMessage(messageReq.getMessage()); // 设置最后一条消息
        chatUser.setLastMessageTime(new Date()); // 设置最后一条消息时间

        // 更新 TiebaChatUser 表中的记录
        int updateResult = chatUserMapper.update(chatUser, new UpdateWrapper<TiebaChatUser>().eq("user_id", getUserId()).eq("chat_user_id", messageReq.getUserOtherId()));
        if (updateResult < 0) {
            return AjaxResult.error("更新最后一条消息失败");
        }

        return AjaxResult.success("聊天记录保存成功");
    }

}
